var express = require('express');
var router = express.Router();
var Category = require('../models/Category');
var Content =  require('../models/Content');

/**
 * 首页
*/
router.get('/', function (req, res) {
    var data = {
        page: Number(req.query.page) || 1,
        limit: 2,
        pages: 0,
        userInfo: req.userInfo,
        category: req.query.category || '',
        categories: [],
        contents: [],
        count: 0
    }

    var where = {};
    if (data.category) {
        where.category = data.category
    }

    // 读取所有的分类信息
    Category.find().then(function (categories) {
        data.categories = categories
        return Content.where(where).count();
    }).then(function(count) {
        data.count = count;
        // 计算总页数
        data.pages = Math.ceil(data.count / data.limit);
        // 取值不能超过pages
        data.page = Math.min(data.page, data.pages)
        // 取值不能小于1
        data.page = Math.max(data.page, 1)

        var skip = (data.page - 1) * data.limit;
        return Content.where(where).find().sort({ _id: -1 }).limit(data.limit).skip(skip).populate(['category', 'user'])
        
    }).then(function(contents) {
        data.contents = contents
        res.render('main/index', data)
    }).catch(err => {
        console.error(err)
    })
})

/**
 * 内容页
*/
router.get('/content', function (req, res) {
    var contentId = req.query.contentId || '';
    var data = {
        userInfo: req.userInfo
    }
    // 读取文章内容
    Category.find().then(function (categories) {
        data.categories = categories;
        return Content.findOne({
            _id: contentId
        }).populate(['category', 'user']);
    }).then(function (con) {
        data.con = con;
        con.views++;
        con.save()
        res.render('main/content', data)
    }).catch(err => {
        console.error(err)
    })
})

module.exports = router